<template>
  <!-- 百度原生API -->
  <div
    ref="baidu_map"
    class="baidu_map_container"
  ></div>
</template>

<script>
import { getAction } from '@/api/manage';
export default {
  mounted() {
    // 创建Map实例,设置地图允许的最小/大级别
    this.map = new BMap.Map(this.$refs.baidu_map, {
      minZoom: 4, // 地图最大缩放级别
      maxZoom: 16, // 地图最小缩放级别
      mapType: BMAP_NORMAL_MAP, //BMAP_HYBRID_MAP【卫星混合地图】、BMAP_SATELLITE_MAP【卫星地图】、BMAP_PERSPECTIVE_MAP【空白地图】、BMAP_NORMAL_MAP【普通地图】
    });

    //左上角，添加默认缩放平移控件
    this.map.addControl(
      new BMap.NavigationControl({
        anchor: BMAP_ANCHOR_TOP_LEFT, //BMAP_ANCHOR_TOP_LEFT、BMAP_ANCHOR_TOP_RIGHT、BMAP_ANCHOR_BOTTOM_LEFT、BMAP_ANCHOR_BOTTOM_RIGHT
        type: BMAP_NAVIGATION_CONTROL_LARGE, //BMAP_NAVIGATION_CONTROL_LARGE、BMAP_NAVIGATION_CONTROL_PAN、BMAP_NAVIGATION_CONTROL_ZOOM、BMAP_NAVIGATION_CONTROL_SMALL
      })
    );

    //添加比例尺
    var opts = { offset: new BMap.Size(80, 22) };
    this.map.addControl(new BMap.ScaleControl(opts));

    //添加默认缩略地图控件[右下角总览]
    this.map.addControl(new BMap.OverviewMapControl());

    // 初始化地图,设置中心点坐标和地图级别
    let point = new BMap.Point(117.205286, 39.156326);
    this.map.centerAndZoom(point, 6);

    //只设置【地图级别】
    // this.map.setZoom(8);

    //添加监听事项
    if (typeof this.map != 'undefined') {
      this.map.addEventListener('zoomend', (e) => {
        let msg =
          '地图级别: ' +
          this.map.getZoom() +
          (this.map.getZoom() > 8 ? ', 示例中只有8级地图,超过的无法显示!' : '');
        this.showMessage(msg);
      });
    }

    //添加地图类型控件【地图/卫星】
    this.map.addControl(
      new BMap.MapTypeControl({
        mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP, BMAP_HYBRID_MAP],
      })
    );

    //开启鼠标滚轮缩放
    this.map.enableScrollWheelZoom(true);
    //开启拖拽
    this.map.disableDragging();
    setTimeout(() => {
      this.map.enableDragging(); //2秒后开启拖拽
      this.showMessage('2s后设置地图可以拖拽');
    }, 2000);

    //获取可视区域
    var bs = this.map.getBounds();
    var bssw = bs.getSouthWest(); //可视区域左下角
    var bsne = bs.getNorthEast(); //可视区域右上角
    this.showMessage(
      '当前地图可视范围是：' +
        bssw.lng.toFixed(6) +
        ', ' +
        bssw.lat.toFixed(6) +
        '到' +
        bsne.lng.toFixed(6) +
        ', ' +
        bsne.lat.toFixed(6)
    );

    //两点测距
    var pointA = new BMap.Point(116.410899, 39.907916); // 创建点坐标A--北京
    var pointB = new BMap.Point(117.211181, 39.013024); // 创建点坐标B--天津
    var polyline = new BMap.Polyline([pointA, pointB], {
      strokeColor: 'blue',
      strokeWeight: 6,
      strokeOpacity: 0.5,
    }); //定义折线
    this.map.addOverlay(polyline);
    this.$message(
      '从北京到天津的距离是：' +
        (this.map.getDistance(pointA, pointB) / 1000).toFixed(2) +
        ' 公里。'
    );

    //添加版权控件
    var cr = new BMap.CopyrightControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT }); //设置版权控件位置
    this.map.addControl(cr); //添加版权控件
    var bs = this.map.getBounds(); //返回地图可视区域
    cr.addCopyright({
      id: 1,
      content:
        "<a href='#' style='font-size:20px;background:yellow'>VUE2学习中</a>",
      bounds: bs,
    });

    //添加动画点图
    var myIcon = new BMap.Icon(
      require('@/assets/train-solid.png'),
      new BMap.Size(20, 20)
    );
    myIcon.setImageSize(new BMap.Size(20, 20));
    var pointC = new BMap.Point(116.410899, 39.907916);
    var marker = new BMap.Marker(pointC, { icon: myIcon }); // 创建标注
    marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    marker.disableDragging(); // 不可拖拽
    var opts = {
      position: pointC, // 指定文本标注所在的地理位置
      offset: new BMap.Size(-5, 30), //设置文本偏移量
    };
    var label = new BMap.Label('文本标注', opts); // 创建文本标注对象
    label.setStyle({
      color: 'red',
      fontSize: '16px',
      height: '25px',
      lineHeight: '25px',
      fontFamily: '微软雅黑',
    });
    marker.setLabel(label); // 为marker定义标签
    this.map.addOverlay(marker); // 将标注添加到地图中
    let content = `
    <p><b>设备号：123</b>
    <p><b>机车号：456</b>
    <p><b>事件：2023-08-29</b>
    `;
    this.addClickHandler(content, marker); //添加单击事件
    setTimeout(() => {
      this.$message('删除描点');
      var allOverlay = this.map.getOverlays();
      for (var i = 0; i < allOverlay.length - 1; i++) {
        console.log(allOverlay[i]);
        try {
          //第一个是路线 没有getLabel属性
          if (allOverlay[i].getLabel().content.indexOf('文本标注') != -1) {
            this.map.removeOverlay(allOverlay[i]);
            return false;
          }
        } catch (error) {}
      }
    }, 1000 * 60 * 10);

    //添加弧线
    let beijingPosition = new BMap.Point(116.432045, 39.910683);
    let hangzhouPosition = new BMap.Point(120.129721, 30.314429);
    let taiwanPosition = new BMap.Point(121.491121, 25.127053);
    var points = [beijingPosition, hangzhouPosition, taiwanPosition];

    var curve = new BMapLib.CurveLine(points, {
      strokeColor: 'blue',
      strokeWeight: 3,
      strokeOpacity: 0.5,
    }); //创建弧线对象
    this.map.addOverlay(curve); //添加到地图中
    curve.enableEditing(); //开启编辑功能

    //添加椭圆
    var pointD = new BMap.Point(115.410899, 39.907916);
    var oval = new BMap.Polygon(this.add_oval(pointD, 0.1, 0.3), {
      strokeColor: 'blue',
      strokeWeight: 6,
      strokeOpacity: 0.5,
    });
    this.map.addOverlay(oval);

    //点聚合
    var MAX = 30;
    var markers = [];
    var pt = null;
    var i = 0;
    for (; i < MAX; i++) {
      pt = new BMap.Point(Math.random() * 40 + 85, Math.random() * 30 + 21);
      markers.push(new BMap.Marker(pt));
    }
    //最简单的用法，生成一个marker数组，然后调用markerClusterer类即可。
    let markerClusterer = new BMapLib.MarkerClusterer(this.map, {
      markers: markers,
    });
    setTimeout(() => {
      this.$message('7s之后清空点聚合');
      markerClusterer.clearMarkers(markers);
    }, 1000 * 7);

    //矢量图
    var vectorPlane = new BMap.Marker(
      new BMap.Point(point.lng + 0.04, point.lat - 0.03),
      {
        // 初始化小飞机Symbol
        icon: new BMap.Symbol(BMap_Symbol_SHAPE_PLANE, {
          scale: 3,
          rotation: 0,
        }),
      }
    );
    this.map.addOverlay(vectorPlane);
    // vectorPlane.hide(); //隐藏
    // vectorPlane.show(); //显示

    //调用后台请求设备列表
    this.showList();
  },
  methods: {
    /**
     * 展示信息
     */
    showMessage(msg) {
      this.$notify({
        message: msg,
        position: 'bottom-right',
      });
    },
    //centre:椭圆中心点,X:横向经度,Y:纵向纬度
    add_oval(centre, x, y) {
      var assemble = new Array();
      var angle;
      var dot;
      var tangent = x / y;
      for (let i = 0; i < 36; i++) {
        angle = ((2 * Math.PI) / 36) * i;
        dot = new BMap.Point(
          centre.lng + Math.sin(angle) * y * tangent,
          centre.lat + Math.cos(angle) * y
        );
        assemble.push(dot);
      }
      return assemble;
    },
    /**
     * 搜索设备列表接口
     */
    showList() {
      getAction('/device/queryDevBasicStateList', {})
        .then((res) => {
          if (res.code == 200) {
            this.devList = res.data;
            console.log('devList', this.devList);
            //判断是否需要填入轨迹
            // this.handleTrack(this.devList);
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },
    /**
     * 添加描点点击事件
     */
    addClickHandler(content, marker) {
      marker.addEventListener('click', (e) => {
        var opts = {
          width: 250, // 信息窗口宽度
          // height: 250, // 信息窗口高度
          // title: '信息窗口', // 信息窗口标题
          enableMessage: true, //设置允许信息窗发送短息
        };
        let p = e.target;
        let point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
        let infoWindow = new BMap.InfoWindow(content, opts); // 创建信息窗口对象
        this.map.openInfoWindow(infoWindow, point); //开启信息窗口
      });
    },
  },
};
</script>
<style scoped lang='scss'>
.baidu_map_container {
  height: 100%;
}
</style>